package com.ms.pda.net

import com.google.gson.JsonSyntaxException
import com.ms.architecture.model.BaseEntry
import okhttp3.Response
import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.TypeParser
import rxhttp.wrapper.utils.GsonUtil
import rxhttp.wrapper.utils.convertTo
import java.io.IOException
import java.lang.reflect.Type

@Parser(name = "Response")
open class Parser<T> : TypeParser<T> {

    protected constructor() : super()

    constructor(type: Type) : super(type)

    @Suppress("UNCHECKED_CAST")
    @Throws(IOException::class)
    override fun onParse(response: Response): T {
        if (response.code != 200) {
            val data: BaseEntry<T> = response.convertTo(BaseEntry::class, *types)
            throw ParseException(response.code.toString(), data.msg, response)
        } else {
            val data: BaseEntry<String> =
                response.convertTo(BaseEntry::class, String::class.java)
            when (data.code) {
                0 -> {
                    var t: T = GsonUtil.getObject(data.data, types[0])
                    if (t == null && types[0] === String::class.java) {
                        t = "" as T
                    }
                    if (t == null) throw JsonSyntaxException("")
                    return t
                }
                2 -> {
                    throw ParseException(
                        data.code.toString(),
                        data.data,
                        response
                    )
                }
                else -> {
                    throw ParseException(
                        data.code.toString(),
                        data.msg,
                        response
                    )
                }
            }
        }
    }
}